using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

using System.Data;
using Prodma.DataAccess.Database;
using Prodma.DataAccess.Models.ViewModels;
using Prodma.DataAccess.DataService;
using Prodma.DataAccess.DataService.ListService;
using Prodma.DataAccess.Helper.Enumerators;
using Prodma.DataAccess.Authorization;
using Prodma.DataAccess.Repositories;
using System.Configuration;
using System.IO;
using Prodma.Panel.Helper;

namespace Prodma.Panel.Controllers
{
    [Authorize]
    public class ContentController : Controller
    {

        #region Repository Setters

        private IContentRepository repository;

        public ContentController() : this(new ContentService()) { }

        public ContentController(IContentRepository _repository)
        {
            repository = _repository;
        }

        #endregion


        #region Index
        [NavigationFilter(MenuAdmins.ContentManagement, AuthorizationType.Read)]
        public ActionResult Index()
        {
            int page = 0;
            if (Request.QueryString["page"] != "" && Request.QueryString["page"] != null)
            {
                page = Convert.ToInt32(Request.QueryString["page"]);
            }

            //ViewData["archiveList"] = ArchiveList.GetList(Convert.ToInt32(ConfigurationManager.AppSettings["defaultArchive"]));
            //ViewData["selectCategoryList"] = CategoryList.GetList();

            //---------------------------------------
            List<SelectList> selectedList = new List<SelectList>();
            selectedList.Add(CategoryList.GetList());
            selectedList.Add(ArchiveList.GetList(Convert.ToInt32(ConfigurationManager.AppSettings["defaultArchive"])));
            ViewData["selectedList"] = selectedList;
            //---------------------------------------

            ViewData["categoryList"] = repository.GetCategoryList();
            ViewData["contentCounts"] = repository.GetCounts();

            if (Request.QueryString["find"] != "" && Request.QueryString["find"] != null)
            {
                Dictionary<string, string> find = new Dictionary<string, string>();
                find.Add("name", Request.QueryString["find"]);
                ViewData["totalRowCount"] = repository.GetTotalRowCount(find);
                return View(repository.GetList(page, find));
            }
            if (Request.QueryString["categoryId"] != "" && Request.QueryString["categoryId"] != null)
            {
                ViewData["totalRowCount"] = repository.GetTotalRowCount(Convert.ToInt32(Request.QueryString["categoryId"]));
                return View(repository.GetList(page, Convert.ToInt32(Request.QueryString["categoryId"])));
            }
            else
            {
                ViewData["totalRowCount"] = repository.GetTotalRowCount();
                return View(repository.GetList(page));
            }
        }
        #endregion


        #region New
        [NavigationFilter(MenuAdmins.ContentManagement, AuthorizationType.Write)]
        public ActionResult New()
        {
            ViewData["archiveList"] = ArchiveList.GetList();
            ViewData["categoryList"] = CategoryList.GetList();
            ViewData["languageList"] = LanguageList.GetList();
            ViewData["stateList"] = StateList.GetList(StateType.General);

            System.Web.HttpContext.Current.Session["contentImage"] = null;

            return View();
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        [NavigationFilter(MenuAdmins.ContentManagement, AuthorizationType.Write)]
        public ActionResult New(FormCollection form)
        {
            ViewData["archiveList"] = ArchiveList.GetList();
            ViewData["categoryList"] = CategoryList.GetList();
            ViewData["languageList"] = LanguageList.GetList();
            ViewData["stateList"] = StateList.GetList(StateType.General);

            tb_Content content = new tb_Content();
            content.Name = Request.Form["name"];
            content.Title = Request.Form["title"];
            content.Content = Request.Form["content"];
            content.Description = Request.Form["description"];
            string image = ConfigurationManager.AppSettings["contentBlankImage"].ToString();
            string imageSmall = ConfigurationManager.AppSettings["contentBlankImage"].ToString();
            if (System.Web.HttpContext.Current.Session["contentImage"] != null)
            {
                image = System.Web.HttpContext.Current.Session["contentImage"].ToString();
                imageSmall = System.Web.HttpContext.Current.Session["contentImageSmall"].ToString();
            }
            content.Folder = Request.Form["folder"];
            content.ImageOriginal = image;
            content.Image = imageSmall;
            content.tb_ArchiveReference.EntityKey = new EntityKey("DataContext.tb_Archive", "Id", Convert.ToInt32(Request.Form["ddlArchive"]));
            content.tb_CategoryReference.EntityKey = new EntityKey("DataContext.tb_Category", "Id", Convert.ToInt32(Request.Form["ddlCategory"]));
            content.SDate = Convert.ToDateTime(Request.Form["sDate"]);
            content.FDate = Convert.ToDateTime(Request.Form["fDate"]);
            content.Date = DateTime.Now;
            content.tb_LanguageReference.EntityKey = new EntityKey("DataContext.tb_Language", "Id", Convert.ToInt32(Request.Form["ddlLanguage"]));
            content.tb_StateReference.EntityKey = new EntityKey("DataContext.tb_State", "Id", Convert.ToInt32(Request.Form["ddlState"]));

            repository.New(content);

            return View();
        }
        #endregion


        #region Edit
        [NavigationFilter(MenuAdmins.ContentManagement, AuthorizationType.Update)]
        public ActionResult Edit()
        {
            int id = Convert.ToInt32(Request.QueryString["id"]);
            ContentVm content = repository.Edit(id);

            ViewData["archiveList"] = ArchiveList.GetList(content.Archive.Id);
            ViewData["categoryList"] = CategoryList.GetList(content.Category.Id);
            ViewData["languageList"] = LanguageList.GetList(content.Language.Id);
            ViewData["stateList"] = StateList.GetList(StateType.General, content.State.Id);
            ViewData["content"] = content.Content;


            string archive = content.Archive.Folder;
            string defaultPath = ConfigurationManager.AppSettings["contentImagePath"];
            string uploadFolder = Server.MapPath(defaultPath) + archive + "\\" + content.Folder;

            Session["uploadImageFolder"] = uploadFolder;
            Session["contentImage"] = content.ImageOriginal;
            Session["contentImageSmall"] = content.Image;

            return View(content);
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        [NavigationFilter(MenuAdmins.ContentManagement, AuthorizationType.Update)]
        public ActionResult Edit(FormCollection form)
        {
            tb_Content content = new tb_Content();
            content.Name = Request.Form["name"];
            content.Title = Request.Form["title"];
            content.Content = Request.Form["content"];
            content.Description = Request.Form["description"];
            string image = ConfigurationManager.AppSettings["contentBlankImage"].ToString();
            string imageSmall = ConfigurationManager.AppSettings["contentBlankImage"].ToString();
            if (System.Web.HttpContext.Current.Session["contentImage"] != null)
            {
                image = System.Web.HttpContext.Current.Session["contentImage"].ToString();
                imageSmall = System.Web.HttpContext.Current.Session["contentImageSmall"].ToString();
            }
            content.Folder = Request.Form["folder"];
            content.ImageOriginal = image;
            content.Image = imageSmall;
            content.tb_ArchiveReference.EntityKey = new EntityKey("DataContext.tb_Archive", "Id", Convert.ToInt32(Request.Form["ddlArchive"]));
            if (Request.Form["ddlCategory"] != "")
            {
                content.tb_CategoryReference.EntityKey = new EntityKey("DataContext.tb_Category", "Id", Convert.ToInt32(Request.Form["ddlCategory"]));
            }
            else
            {
                content.tb_CategoryReference.EntityKey = null;
            }
            content.SDate = Convert.ToDateTime(Request.Form["sDate"]);
            content.FDate = Convert.ToDateTime(Request.Form["fDate"]);
            content.Date = DateTime.Now;
            content.tb_LanguageReference.EntityKey = new EntityKey("DataContext.tb_Language", "Id", Convert.ToInt32(Request.Form["ddlLanguage"]));
            content.tb_StateReference.EntityKey = new EntityKey("DataContext.tb_State", "Id", Convert.ToInt32(Request.Form["ddlState"]));

            int id = Convert.ToInt32(Request.Form["id"]);
            int page = 0;
            if (Request.QueryString["page"] != "" && Request.QueryString["page"] != null)
            {
                page = Convert.ToInt32(Request.QueryString["page"]);
            }

            repository.Update(id, content);

            return RedirectToAction("edit/?id=" + id + "&page=" + page);
        }
        #endregion


        #region Delete
        [NavigationFilter(MenuAdmins.ContentManagement, AuthorizationType.Delete)]
        public ActionResult Delete()
        {
            string[] idList = Request.QueryString["idList"].Split(',');

            foreach (string id in idList)
            {
                string deleteId = id.Substring(3, id.Length - 3);
                repository.Delete(Convert.ToInt32(deleteId));
            }

            return RedirectToAction("index");
        }
        #endregion


        #region Set Active && Passive
        [NavigationFilter(MenuAdmins.ContentManagement, AuthorizationType.Update)]
        public ActionResult SetActive()
        {
            string[] idList = Request.QueryString["idList"].Split(',');

            foreach (string id in idList)
            {
                string currentId = id.Substring(3, id.Length - 3);
                repository.SetActive(Convert.ToInt32(currentId));
            }

            return RedirectToAction("index");
        }
        [NavigationFilter(MenuAdmins.ContentManagement, AuthorizationType.Update)]
        public ActionResult SetPassive()
        {
            string[] idList = Request.QueryString["idList"].Split(',');

            foreach (string id in idList)
            {
                string currentId = id.Substring(3, id.Length - 3);
                repository.SetPassive(Convert.ToInt32(currentId));
            }

            return RedirectToAction("index");
        }
        #endregion


        #region Content Image Operations

        public ActionResult Image()
        {
            return View();
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        [NavigationFilter(MenuAdmins.ContentManagement, AuthorizationType.Write)]
        public ActionResult UploadImage()
        {
            foreach (string inputTagName in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[inputTagName] as HttpPostedFileBase;
                string[] fileNames = file.FileName.Split('\\');
                string fileName = fileNames[fileNames.Length - 1];

                if (file.ContentLength > 0)
                {
                    string destinationPath;
                    if (Session["uploadImageFolder"] == null)
                    {
                        destinationPath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["contentImagePath"].ToString());
                    }
                    else
                    {
                        destinationPath = Session["uploadImageFolder"].ToString();
                    }
                    string filePath = Path.Combine(destinationPath, Path.GetFileName(file.FileName));
                    file.SaveAs(filePath);

                    string thumbImage = fileName.Substring(0, fileName.Length - 4) + "_small" + fileName.Substring(fileName.Length - 4, 4);
                    
                    ImageResizer.CreateThumbnailImage(filePath, destinationPath + "\\" + thumbImage, 100, 75);

                    System.Web.HttpContext.Current.Session["contentImage"] = fileName;
                    System.Web.HttpContext.Current.Session["contentImageSmall"] = thumbImage;
                }
            }
            return RedirectToAction("image", "content");
        }

        [NavigationFilter(MenuAdmins.ContentManagement, AuthorizationType.Delete)]
        public ActionResult RemoveImage()
        {
            int id;
            if (Request.QueryString["id"] != "")
            {
                id = Convert.ToInt32(Request.QueryString["id"]);
            }
            else
            {
                return RedirectToAction("image", "content");
            }

            System.Web.HttpContext.Current.Session["contentImage"] = ConfigurationManager.AppSettings["contentBlankImage"].ToString();
            repository.RemoveImage(id);

            return RedirectToAction("image", "content");
        }
        #endregion


        #region Order Operation

        public ActionResult OrderUp()
        {
            int contentId = Convert.ToInt32(Request.QueryString["id"]);
            int orderNo = Convert.ToInt32(Request.QueryString["orderNo"]);
            int category = Convert.ToInt32(Request.QueryString["category"]);
            int archive = Convert.ToInt32(Request.QueryString["archive"]);

            ContentOrderVm contentOrder = new ContentOrderVm();
            contentOrder.Content = contentId;
            contentOrder.Archive = archive;
            contentOrder.Category = category;
            contentOrder.OrderNo = orderNo;

            repository.OrderUp(contentId, contentOrder);

            return RedirectToAction("/index/?page=" + Request.QueryString["page"]);
        }

        public ActionResult OrderDown()
        {
            int contentId = Convert.ToInt32(Request.QueryString["id"]);
            int orderNo = Convert.ToInt32(Request.QueryString["orderNo"]);
            int category = Convert.ToInt32(Request.QueryString["category"]);
            int archive = Convert.ToInt32(Request.QueryString["archive"]);

            ContentOrderVm contentOrder = new ContentOrderVm();
            contentOrder.Content = contentId;
            contentOrder.Archive = archive;
            contentOrder.Category = category;
            contentOrder.OrderNo = orderNo;

            repository.OrderDown(contentId, contentOrder);

            return RedirectToAction("/index/?page=" + Request.QueryString["page"]);
        }

        public ActionResult SetOrder()
        {
            int contentId = Convert.ToInt32(Request.QueryString["id"]);
            int orderNo = Convert.ToInt32(Request.QueryString["orderNo"]);
            int archive = Convert.ToInt32(Request.QueryString["archive"]);
            int category = Convert.ToInt32(Request.QueryString["category"]);
            int setOrderNo = Convert.ToInt32(Request.QueryString["setOrderNo"]);

            int page = 0;
            if (Request.QueryString["page"] != "" && Request.QueryString["page"] != null)
            {
                page = Convert.ToInt32(Request.QueryString["page"]);
            }
            if (setOrderNo < 0)
            {
                return RedirectToAction("/index/?page=" + page);
            }

            ContentOrderVm contentOrder = new ContentOrderVm();
            contentOrder.Content = contentId;
            contentOrder.Archive = archive;
            contentOrder.Category = category;
            contentOrder.OrderNo = orderNo;
            contentOrder.SetOrderNo = setOrderNo;

            repository.SetOrder(contentId, contentOrder);

            return RedirectToAction("/index/?page=" + page);
        }

        #endregion


        #region SetDefaultArchive

        public ActionResult SetDefaultArchive()
        {
            if (Request.QueryString["categoryId"] != "" && Request.QueryString["categoryId"] != null)
            {
                int categoryId = Convert.ToInt32(Request.QueryString["categoryId"]);
                int archiveId = Convert.ToInt32(Request.QueryString["archiveId"]);
                repository.SetDefaultArchive(archiveId);

                return RedirectToAction("index/?categoryId=" + categoryId);
            }
            else
            {
                int archiveId = Convert.ToInt32(Request.QueryString["archiveId"]);
                repository.SetDefaultArchive(archiveId);

                return RedirectToAction("index");
            }
        }

        #endregion


        public ActionResult CreateFolder(string folder, string archiveFolder)
        {
            string archive = ArchiveList.GetArchiveFolderName(Convert.ToInt32(archiveFolder));
            string defaultImagePath = ConfigurationManager.AppSettings["contentImagePath"];
            string defaultFilePath = ConfigurationManager.AppSettings["contentFilePath"];
            string uploadImageFolder = Server.MapPath(defaultImagePath) + archive + "\\" + folder;
            string uploadFileFolder = Server.MapPath(defaultFilePath) + archive + "\\" + folder;
            Directory.CreateDirectory(uploadImageFolder);
            Directory.CreateDirectory(uploadFileFolder);

            Session["uploadImageFolder"] = uploadImageFolder;

            return RedirectToAction("new");
        }

        public void MoveFolder(string sourceFolder, string sourceArchiveFolder, string destinationFolder, string destinationArchiveFolder)
        {
            if (sourceFolder == destinationFolder)
            {
                return;
            }

            string defaultImagePath = ConfigurationManager.AppSettings["contentImagePath"];
            string defaultFilePath = ConfigurationManager.AppSettings["contentFilePath"];

            string oldArchive = ArchiveList.GetArchiveFolderName(Convert.ToInt32(sourceArchiveFolder));
            string newArchive = ArchiveList.GetArchiveFolderName(Convert.ToInt32(destinationArchiveFolder));

            if (sourceFolder == "")
            {
                Directory.CreateDirectory(Server.MapPath(defaultImagePath) + newArchive + "\\" + destinationFolder);
                Directory.CreateDirectory(Server.MapPath(defaultFilePath) + newArchive + "\\" + destinationFolder);

                Session["uploadImageFolder"] = Server.MapPath(defaultImagePath) + newArchive + "\\" + destinationFolder;

                return;
            }

            string sourceUploadImageFolder = Server.MapPath(defaultImagePath) + oldArchive + "\\" + sourceFolder;
            string sourceUploadFileFolder = Server.MapPath(defaultFilePath) + oldArchive + "\\" + sourceFolder;

            string destinationUploadImageFolder = Server.MapPath(defaultImagePath) + newArchive + "\\" + destinationFolder;
            string destinationUploadFileFolder = Server.MapPath(defaultFilePath) + newArchive + "\\" + destinationFolder;

            Directory.Move(sourceUploadImageFolder, destinationUploadImageFolder);
            Directory.Move(sourceUploadFileFolder, destinationUploadFileFolder);

            Session["uploadImageFolder"] = destinationUploadImageFolder;
        }

    }
}
